package com.example.good.controller;

import com.example.good.service.ex.*;
import com.example.good.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**控制层的基类  编写统一的异常捕获*/
public class BaseController {
    public static final int OK = 200;
    @ExceptionHandler({ServiceException.class})
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UsernameDuplicatedException){
            result.setState(4000);
            result.setMessage("用户名被占用");
        }else if (e instanceof UserNotFoundException){
            result.setState(4001);
            result.setMessage("用户不存在");
        }else if (e instanceof PasswordNotMatchException){
            result.setState(4002);
            result.setMessage("密码错误");
        }else if (e instanceof AddressCountLimitException){
            result.setState(4003);
            result.setMessage("地址超出上限");
        }else if (e instanceof AddressNotFoundException){
            result.setState(4004);
            result.setMessage("地址不存在");
        }else if (e instanceof AccessDeniedException){
            result.setState(4005);
            result.setMessage("非法访问");
        }else if (e instanceof PhoneErrorException){
            result.setState(4006);
            result.setMessage("用户绑定的手机号不正确");
        }else if (e instanceof InsertException){
            result.setState(5000);
            result.setMessage("插入异常");
        }else if (e instanceof UpdateException){
            result.setState(5001);
            result.setMessage("更新异常");
        }else if (e instanceof DeleteException){
            result.setState(5002);
            result.setMessage("删除异常");
        }else if (e instanceof VerificationCodeErrorException){
            result.setState(7000);
            result.setMessage("验证码错误");
        }
        return result;
    }
    protected final Integer getUidFromSession(
            HttpSession session){
        System.out.println(session);
        return Integer.valueOf(session.getAttribute("good_uid").toString());
    }
    protected final String getUsernameFromSession(
            HttpSession session){
        return session.getAttribute("good_usn").toString();
    }
}
